/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7

import SMSHelper 1.0


import "DCDataClasses.js" as DCDATA

import "privacysettings.js" as PS

Rectangle
{
    id: joinconfirmationdlg
    border.color: "#363264"
    visible: false
    width: 300
    height: 240
    color: "white"


    property string karpoid: "" // user's own karpoid
    property string datacloudurl: ""

    property string fromlatitude: "0"
    property string fromlongitude: "0"

    property string picklatitude: "0"
    property string picklongitude: "0"

    property string pickdistance: "0"
    property string picktraveltime: "0"

    signal picklocation()
    signal drawImageOnMap(string id, double latitude, double longitude, string img, int xOffset, int yOffset)
    signal findRoute(double fromlatitude, double fromlongitude, double picklatitude, double picklongitude)
    signal clearMap()


    property string joinroutename: ""
    property string joinrouteownername:  ""
    property string joinrouteownerphone: ""
    property string joinroutekarpoid: ""
    property string joinrouteownerkarpoid: ""
    property string joincarpoolkarpoid: ""

    property string requestkarpoid: ""

    function setInfo(routename,routedesc,routetime,routerepeat,ownername,ownerhometown,ownerphone,routefrom,routeto,routekarpoid,carpoolkarpoid,ownerkarpoid,ownerphonepassprivacy)
    {

        joinroutename = routename
        joinrouteownername = ownername
        joinrouteownerphone = ownerphonepassprivacy
        joinroutekarpoid = routekarpoid
        joinrouteownerkarpoid = ownerkarpoid
        joincarpoolkarpoid = carpoolkarpoid

        fromlatitude = routefrom.latitude
        fromlongitude = routefrom.longitude

        picklatitude = "0"
        picklongitude = "0"
        picklocationid.text = "<b>Pick location:</b><br>not set"
        traveltimeid.text = "<b>From start: -</b>"
        traveltimeid.visible = false


        textmodel.clear()
        textmodel.append({"title":"Name","content":routename})
        textmodel.append({"title":"Description","content":routedesc})
        textmodel.append({"title":"From","content":routefrom.street + ", " + routefrom.city})
        textmodel.append({"title":"To","content":routeto.street + ", " + routeto.city})
        textmodel.append({"title":"Distance","content":routeto.distance})
        textmodel.append({"title":"Traveltime","content":DCDATA.secondToHMS(routeto.traveltime)})
        textmodel.append({"title":"Owner","content":ownername + ", " + ownerphone + ", " + ownerhometown})


        console.log("\r\n\r\n JOINCONF::PRIVACY: showmyname = " + PS.showmyname + ", showmyphone = " + PS.showmyphone + ", showmyhometown = " + PS.showmyhometown + "\r\n\r\n")
    }


    Rectangle
    {
        id: titlerect
        height: 20
        color: "#418cb1"
        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.topMargin: 0

        Text {
            id: titleid
            anchors.fill: parent
            anchors.leftMargin: 5
            text: "<b>Route information</b>"

            font.pixelSize: 14
        }

        MouseArea {
            id: titlerectmousearea
            anchors.fill: parent

            drag.target: joinconfirmationdlg
            drag.axis: Drag.XandYAxis
            drag.minimumX: 0
            drag.maximumX: 1000
            drag.minimumY: 0
            drag.maximumY: 1000
        }
    }

    Rectangle {
        id: infoid
        height: 100
        color: "white"
        border.color: "black"
        clip: true
        anchors.left:  parent.left
        anchors.leftMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 10
        anchors.top:  titlerect.bottom
        anchors.topMargin: 5

        ListModel
        {
            id: textmodel

        }

        Component {
            id: textDelegate

            Item {
                width: infoid.width; height: 30
                Column {
                    Text { text: '<b>' + title + '</b>'; font.pixelSize: 12; anchors.left:  parent.left; anchors.leftMargin: 5 }
                    Text { text: content; font.pixelSize: 12; anchors.left:  parent.left; anchors.leftMargin: 5;}
                }
            }
        }

        ListView {
            anchors.fill: parent

            boundsBehavior: Flickable.StopAtBounds

            model: textmodel
            delegate: textDelegate

        }
    }


    Text {
        id: picklocationid
        text: "<b>Pick location:</b><br>not set"
        anchors.left: parent.left
        anchors.leftMargin: 5
        anchors.right: parent.right
        anchors.top: infoid.bottom
        anchors.topMargin: 5
        font.pixelSize: 12
    }

    Text {
        id: traveltimeid
        text: "<b>From start: -</b>"
        visible:  false
        anchors.left: parent.left
        anchors.leftMargin: 5
        anchors.right: parent.right
        anchors.top: picklocationid.bottom
        anchors.topMargin: 5
        font.pixelSize: 12
    }

    function locationPicked(lat,lon)
    {
        picklocationid.text = "<b>Pick location:</b><br>" + lat + ", " + lon

        picklatitude = lat
        picklongitude = lon

        messagebox.showInfo("Calculation traveltime...")
        joinconfirmationdlg.findRoute(fromlatitude, fromlongitude, picklatitude,picklongitude);

        joinconfirmationdlg.drawImageOnMap("picklocation", picklatitude, picklongitude, "./qml/carpool/pickloc.png", -10,-34)

    }

    function setDistanceAndTraveltime(distance, traveltime)
    {
        pickdistance = distance/1000
        picktraveltime = DCDATA.secondToHMS(traveltime)

        var res = pickdistance + " km, " + picktraveltime

        traveltimeid.text = "<b>From start: </b><br>"  + res
        traveltimeid.visible = true

        messagebox.visible = false
    }

    PushButton
    {
        id: picklocationpoint
        width: 110
        label: "Pick location..."
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 5

        onButtonpressed:
        {

            joinconfirmationdlg.picklocation()
        }
    }



    PushButton
    {
        id: dojoinrequest
        width: 110
        label: "Send request..."
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.right: picklocationpoint.left
        anchors.rightMargin: 5

        onButtonpressed:
        {
            requestsending.showmyname = PS.showmyname
            requestsending.showmyhometown = PS.showmyhometown
            requestsending.showmyphone = PS.showmyphone
            requestsending.visible = true
        }
    }


    PushButton
    {
        id: cancel
        width: 60
        label: "Cancel"
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.right: dojoinrequest.left
        anchors.rightMargin: 5

        onButtonpressed:
        {
            joinconfirmation.visible = false;

        }
    }


    Rectangle
    {
        id: requestsending
        visible: false
        anchors.fill: parent

        property string showmyname: "0"
        property string showmyhometown: "0"
        property string showmyphone: "0"



        Rectangle
        {
            id: requesttextrect
            height: 20
            color: "#418cb1"
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.topMargin: 0

            Text {
                id: requesttextid
                anchors.fill: parent
                anchors.leftMargin: 5
                text: "<b>Request text</b>"

                font.pixelSize: 14
            }

        }


        Rectangle {
            id: requesttextinputrectangle
            height: 14*10
            color: "#ffffff"
            anchors.right: parent.right
            anchors.rightMargin: 10
            anchors.left: parent.left
            anchors.leftMargin: 5
            anchors.top: requesttextrect.bottom
            anchors.topMargin: 5


            border.color: "#000901"

            TextEdit  {
                id: requesttextinput
                text: "I'd like to join your route '" + joinroutename + "'"
                anchors.leftMargin: 3
                anchors.topMargin: 3
                anchors.fill: parent
                selectionColor: "#316ac5"
                wrapMode: TextEdit.Wrap
                font.pixelSize: 12
            }
        }


        Rectangle
        {

            id: privacyrect
            color: "#00000000"
            height: 22
            anchors.left: parent.left
            anchors.leftMargin: 5
            anchors.right: parent.right
            anchors.top: requesttextinputrectangle.bottom
            anchors.topMargin: 5
            z: 4

            Text {
                id: privacyid
                width:50
                text: "Show my"
                anchors.left: parent.left
                anchors.leftMargin: 5
                anchors.verticalCenter: privacyrect.verticalCenter
                font.pixelSize: 12
            }

            CheckBox
            {
                id: showmynamecheckbox
                width: 70
                label: "name"
                textfontpixelsize: 12
                selected: (requestsending.showmyname == "1")
                anchors.leftMargin: 0
                anchors.bottomMargin: 0
                anchors.topMargin: 0
                anchors.left: privacyid.right
                anchors.bottom: parent.bottom
                anchors.top: parent.top

                onSelectionchanged:
                {
                    isSelected?requestsending.showmyname="1":requestsending.showmyname="0"
                }
            }

            CheckBox
            {
                id: showmyphonecheckbox
                width: 70
                label: "phone"
                textfontpixelsize: 12
                selected: (requestsending.showmyphone == "1")
                anchors.leftMargin: 0
                anchors.bottomMargin: 0
                anchors.topMargin: 0
                anchors.left: showmynamecheckbox.right
                anchors.bottom: parent.bottom
                anchors.top: parent.top

                onSelectionchanged:
                {
                    isSelected?requestsending.showmyphone="1":requestsending.showmyphone="0"
                }
            }

            CheckBox
            {
                id: showmynhometowncheckbox
                width: 95
                label: "hometown"
                textfontpixelsize: 12
                selected: (requestsending.showmyhometown == "1")
                anchors.leftMargin: 0
                anchors.bottomMargin: 0
                anchors.topMargin: 0
                anchors.left: showmyphonecheckbox.right
                anchors.bottom: parent.bottom
                anchors.top: parent.top

                onSelectionchanged:
                {
                    isSelected?requestsending.showmyhometown="1":requestsending.showmyhometown="0"
                }
            }


        }

        PushButton
        {
            id: sendid
            label: "Send"
            width: 80
            anchors.right: parent.right
            anchors.rightMargin: 10
            anchors.top: privacyrect.bottom
            anchors.topMargin: 20


            onButtonpressed:
            {

                if (joinrouteownerphone == "" || joinrouteownerphone == "NA")
                {
                    messagebox.showInfo("The phone number of the route's owner<br>is unknown. Can't send the request.")
                }
                else
                {

                    var joinreq = new DCDATA.DCJoinRequest()
                    joinreq.joinrequestkarpoid = "0" // this is set in the server side
                    joinreq.carpoolkarpoid = joincarpoolkarpoid
                    joinreq.routekarpoid = joinroutekarpoid
                    joinreq.ownerkarpoid = joinrouteownerkarpoid
                    joinreq.travellerkarpoid = karpoid
                    joinreq.showname = requestsending.showmyname
                    joinreq.showhometown = requestsending.showmyhometown
                    joinreq.showphone = requestsending.showmyphone
                    joinreq.message = requesttextinput.text
                    joinreq.picklat = joinconfirmationdlg.picklatitude
                    joinreq.picklon = joinconfirmationdlg.picklongitude

                    DCDATA.send(joinreq,datacloudurl,"savejoinrequest",savejoinrequestcb)

                }
            }

            function savejoinrequestcb(response)
            {
                console.log("savejoinrequestcb: " + JSON.stringify(response))

                try
                {
                    if (response.isError)
                    {
                        messagebox.text = "Failed to save the joinrequest. " + response.errorString
                    }
                    else
                    {
                        joinconfirmationdlg.requestkarpoid = response.joinrequestkarpoid

                        // send joinrequest sms
                        var message = "You have a joinrequest. See the link " + datacloudurl + "/Membership?joinrequestid=" + joinconfirmationdlg.requestkarpoid
                        var phone = joinconfirmationdlg.joinrouteownerphone


                        console.log("SMS KUTSU:\r\nPhone  : " + phone + "\r\nContent: " + message)

                        // See smshelper.sendms method in smshelper.cpp => if not symbian or maemo5/6 then just return true
                        if (!smshelper.sendsms(phone, message))
                        {
                            messagebox.text = "Failed to send joinrequest sms"
                            messagebox.show("")
                        }
                        else
                        {
                            messagebox.text = "Join request sent."
                            messagebox.onOkTodo = "close"
                            messagebox.show("")

                        }



                    }

                }
                catch (e)
                {
                    messagebox.text = "Failed to send joinrequest sms"
                    messagebox.show("")
                }


            }

        }

        PushButton
        {
            id: cancelid
            label: "Cancel"
            width: 80
            anchors.right: sendid.left
            anchors.rightMargin: 20
            anchors.top: privacyrect.bottom
            anchors.topMargin: 20

            onButtonpressed:
            {
                requestsending.visible = false
            }

        }

    }

    SMSHelper
    {
        id: smshelper

        onDebugMsg:
        {
            console.log("SMSHELPER: " + dbgmsg)
        }

        onErrorMsg:
        {
            console.log("SMSHELPER: " + errormsg)
        }


    }

    MessageBox
    {
        id: messagebox

        function showInfo(msg)
        {
            messagebox.text = msg
            messagebox.show("")
        }

        property string onOkTodo: "" // close

        onOk:
        {
            console.log("MessageBox:onOk => " + onOkTodo)
            if (onOkTodo == "close")
            {
                joinconfirmationdlg.clearMap()
                messagebox.visible = false
                requestsending.visible = false
                joinconfirmationdlg.visible = false


            }

            onOkTodo = ""
        }

        onCancel:
        {
            onOkTodo = ""
        }

    }

}
